package ihero

import (
	"gitee.com/tietang/terrace-go/v2/base"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/context"
	"github.com/kataras/iris/v12/hero"
	log "github.com/sirupsen/logrus"
	"net/http"
)

var errorHandler hero.ErrorHandler = hero.ErrorHandlerFunc(func(ctx iris.Context, err error) {
	if err == nil {
		return
	}
	if err != hero.ErrStopExecution {
		if status := ctx.GetStatusCode(); status == 0 || !context.StatusCodeNotSuccessful(status) {
			ctx.StatusCode(hero.DefaultErrStatusCode)
		}
		_, _ = ctx.WriteString(err.Error())
	}
	r := base.Res{
		Code: base.ResCodeInnerServerError,
	}
	r.Message = err.Error()
	ctx.JSON(&r)
	log.Error(err)
	ctx.StatusCode(http.StatusInternalServerError)
	ctx.StopExecution()
})
